<?php

namespace app\api\controller;

use app\api\logic\DulizhanLogic;
use think\facade\Db;
use app\data\util\HttpUtil;

class DulizhanPackage
{
    /**
     * @desc  整理货号跟件数
     */
    public function AddSKUDetails(){
        $t1       = microtime(true);
        // $count = Db::connect('DULIZHAN')
        //     ->name('order')
        //     ->where('created_at',">",1711555200)
        //     ->where('created_at',"<",1714579200)
        //     ->where('skuinfo_time',"=",0)
        //     ->order('created_at desc')
        //     ->count();
            $count = 45000;
        $pageSize = 500; // 每500条记录读取一次
        // $page     = ceil($count / $pageSize);
        $executedCount = 0;
        // for ($i = 1; $i <= $page; $i++){
            $list = Db::connect('DULIZHAN')
                ->name('order')
                ->field('id')
                ->where('created_at',">",1711555200)
                ->where('created_at',"<",1714579200)
                ->where('skuinfo_time',"=",0)
                ->order('created_at asc')
                ->select()
                ->toArray();
                // dump($list);die;
                
            foreach ($list as $v){
                (new DulizhanLogic())->AddSKUDetails($v);
                $executedCount++;
                $num = $count - $executedCount;
                echo PHP_EOL . "总计:" . $count . '条' . '-----' . "已执行:" . $executedCount . '-----' . '剩余:' . $num . '条' . PHP_EOL;
            }
        // }
        echo PHP_EOL . "get_webhook_infos-定时执行总耗时:" . round(microtime(true) - $t1, 3) . PHP_EOL;
    }
    /**
     * @desc  整理订单是否被结算
     */
    public function HasTheOrderBeenSettled(){
        $t1       = microtime(true);
        $count = Db::connect('DULIZHAN')
            ->name('jiesuan')
            ->where('status',"=",null)
            ->count();
        $pageSize = 500; // 每500条记录读取一次
        $page     = ceil($count / $pageSize);
        $executedCount = 0;
        for ($i = 1; $i <= $page; $i++){
            $list = Db::connect('DULIZHAN')
                ->name('jiesuan')
                ->field('order_id')
                ->where('status',"=",null)
                ->paginate($pageSize)
                ->toArray();
            foreach ($list['data'] as $v){
                (new DulizhanLogic())->HasTheOrderBeenSettled($v);
                $executedCount++;
                $num = $count - $executedCount;
                echo PHP_EOL . "总计:" . $count . '条' . '-----' . "已执行:" . $executedCount . '-----' . '剩余:' . $num . '条' . PHP_EOL;
            }
        }
        echo PHP_EOL . "get_webhook_infos-定时执行总耗时:" . round(microtime(true) - $t1, 3) . PHP_EOL;
    }

    /**
     * @desc  整理订单是否匹配到运营跟渠道
     */
    public function MatchingToOperationsAndChannels(){
        $t1       = microtime(true);
        $count = Db::connect('DULIZHAN')
            ->name('customerjourney')
            ->where('status',0)
            ->count();
        $pageSize = 500; // 每500条记录读取一次
        $page     = ceil($count / $pageSize);
        $executedCount = 0;
        for ($i = 1; $i <= $page; $i++){
            $list = Db::connect('DULIZHAN')
                ->name('customerjourney')
                ->where('status',0)
                ->order('order_number desc')
                ->paginate($pageSize)
                ->toArray();
            foreach ($list['data'] as $v){
                (new DulizhanLogic())->MatchingToOperationsAndChannels($v);
                $executedCount++;
                $num = $count - $executedCount;
                echo PHP_EOL . "总计:" . $count . '条' . '-----' . "已执行:" . $executedCount . '-----' . '剩余:' . $num . '条' . PHP_EOL;
            }
        }
        echo PHP_EOL . "get_webhook_infos-定时执行总耗时:" . round(microtime(true) - $t1, 3) . PHP_EOL;
    }

    /**
     * @desc  修改客户订阅状态
     */
    public function update_customer_status(){
        $t1       = microtime(true);
        $count = Db::connect('DULIZHAN')
            ->name('customer')
            ->where('is_published', '=' , 0)
            ->where('site_id', '=' , 121)
            ->where('email', '<>' , "")
            ->order('customers_timea asc,ycreated_at asc')
            ->count();
        $site = Db::connect('DULIZHAN')
            ->name('site')
            ->where('id', 121)
            ->find();
        $pageSize = 500; // 每500条记录读取一次
        $page     = ceil($count / $pageSize);
        $executedCount = 0;
        for ($i = 1; $i <= $page; $i++){
            $list = Db::connect('DULIZHAN')
                ->name('customer')
                ->where('is_published', '=' , 0)
                ->where('site_id', '=' , 121)
                ->where('email', '<>' , "")
                ->order('customers_timea asc,ycreated_at asc')
                ->paginate($pageSize)
                ->toArray();
            foreach ($list['data'] as $v){
                //客户API开始
                $post['customer']['id'] = $v['customer_id'];
                $post['customer']['accepts_marketing'] = true;
                $post['customer']['verified_email'] = true;
                $post['customer']['accepts_marketing_updated_at'] = '2024-06-20T15:32:56-04:00';
                $url = $site['site_url'] . "/admin/api/2021-07/customers/" . $v['customer_id'] . ".json";
                $data2 =  HttpUtil::shopifyPutUrl($url, $post, $site);
                $data2 = json_decode($data2, true);
                if (isset($data2['errors']) && !empty($data2['errors'])) {
                    $row['customers_timea'] = '99999999999';
                } else {
                    $row['is_published'] = 1;
                    $row['customers_timea'] = time();
                }
                Db::connect('DULIZHAN')
                    ->name('customer')
                    ->where('id', $v['customer_id'])
                    ->update($row);
                //客户API结束

                $executedCount++;
                $num = $count - $executedCount;
                echo PHP_EOL . "总计:" . $count . '条' . '-----' . "已执行:" . $executedCount . '-----' . '剩余:' . $num . '条' . PHP_EOL;
            }
        }
        echo PHP_EOL . "get_webhook_infos-定时执行总耗时:" . round(microtime(true) - $t1, 3) . PHP_EOL;
    }
    /**
     * @desc  查找订单相关信息
     */
    public function SearchForOrderRelatedInformation(){
        $t1       = microtime(true);
        $count = Db::connect('DULIZHAN')
            ->name('ztest_test1')
            ->count();
        $pageSize = 1000; // 每500条记录读取一次
        $page     = ceil($count / $pageSize);
        $executedCount = 0;
        for ($i = 1; $i <= $page; $i++){
            $list = Db::connect('DULIZHAN')
                ->name('ztest_test1')
                ->paginate($pageSize)
                ->toArray();
            foreach ($list['data'] as $v){
                $row = [];
                $order = Db::connect('DULIZHAN')
                    ->name('order')
                    ->where('order_number',$v['a'])
                    ->where('site_id',121)
                    ->find();
                if(!empty($order)){
                    $row['b'] = $order['financial_status'];
                    $row['c'] = $order['fulfillment_status'];
                }
                
                Db::connect('DULIZHAN')
                    ->name('ztest_test1')
                    ->where('id', $v['id'])
                    ->update($row);

                $executedCount++;
                $num = $count - $executedCount;
                echo PHP_EOL . "总计:" . $count . '条' . '-----' . "已执行:" . $executedCount . '-----' . '剩余:' . $num . '条' . PHP_EOL;
            }
        }
        echo PHP_EOL . "get_webhook_infos-定时执行总耗时:" . round(microtime(true) - $t1, 3) . PHP_EOL;
    }
    /**
     * @desc  运营标签同步到系统    
     */
    public function SynchronizeOperationTagsToTheSystem(){
        $t1       = microtime(true);
        $count = Db::connect('DULIZHAN')
            ->name('customerjourneywoob')
            ->where('status_tags',0)
            ->count();

        $where['b.created_at'] =  ['between', ['1711900800', time()]];
        $count = Db::connect('DULIZHAN')
            ->name('customerjourneywoob')
            ->alias('a')
            ->join('qu_order b','b.order_number = a.order_number', 'left')
            ->where($where)
            ->select()
            ->toarray();

        $pageSize = 1000; // 每500条记录读取一次
        $page     = ceil($count / $pageSize);
        $executedCount = 0;
        for ($i = 1; $i <= $page; $i++){
            $list = Db::connect('DULIZHAN')
                ->name('ztest_test1')
                ->paginate($pageSize)
                ->toArray();
            foreach ($list['data'] as $v){
                $row = [];
                $order = Db::connect('DULIZHAN')
                    ->name('order')
                    ->where('order_number',$v['a'])
                    ->where('site_id',121)
                    ->find();
                if(!empty($order)){
                    $row['b'] = $order['financial_status'];
                    $row['c'] = $order['fulfillment_status'];
                }
                
                Db::connect('DULIZHAN')
                    ->name('ztest_test1')
                    ->where('id', $v['id'])
                    ->update($row);

                $executedCount++;
                $num = $count - $executedCount;
                echo PHP_EOL . "总计:" . $count . '条' . '-----' . "已执行:" . $executedCount . '-----' . '剩余:' . $num . '条' . PHP_EOL;
            }
        }
        echo PHP_EOL . "get_webhook_infos-定时执行总耗时:" . round(microtime(true) - $t1, 3) . PHP_EOL;
    }
    /**
     * @desc  shopify交易记录    
     */
    public function ShopifyTransactionRecords(){
        $t1       = microtime(true);
        // $count = Db::connect('DULIZHAN')
        //     ->name('order')
        //     ->where('site_id',121)
        //     ->where('fulfillment_status',"unshipped")
        //     ->where('created_at',">=", 1711814400)
        //     ->where('created_at',"<=", 1714492800)
        //     ->count();
        $count = 1000;
        // $pageSize = 1000; // 每500条记录读取一次
        // $page     = ceil($count / $pageSize);
        $executedCount = 0;
        // for ($i = 1; $i <= $page; $i++){
            $list = Db::connect('DULIZHAN')
                ->name('order')
                ->field('id')
                ->where('site_id',121)
                ->where('fulfillment_status',"unshipped")
                ->where('created_at',">=", 1711814400)
                ->where('created_at',"<=", 1714492800)
                ->select()
                ->toarray();
                
            $site = Db::connect('DULIZHAN')
                ->name('site')
                ->where('id', 121)
                ->find();
            foreach ($list as $v){
                $this->update_order_transactions($v['id'],$site);

                $executedCount++;
                $num = $count - $executedCount;
                echo PHP_EOL . "总计:" . $count . '条' . '-----' . "已执行:" . $executedCount . '-----' . '剩余:' . $num . '条' . PHP_EOL;
            }
        // }
        echo PHP_EOL . "get_webhook_infos-定时执行总耗时:" . round(microtime(true) - $t1, 3) . PHP_EOL;
    }

    public function update_order_transactions($id,$site)
    {
        $url = $site['site_url'] . "/admin/api/2023-07/orders/" . $id . "/transactions.json";
        $data = HttpUtil::shopifyGetUrl($url, $site['apikey'], $site['apisecret']);
        $data = json_decode($data, true);
        if (isset($data['transactions']) && !empty($data['transactions'])) {
            $transactions = $data['transactions'];
            $site = Db::connect('DULIZHAN')
                ->name('order_transactions')
                ->where('order_id', $id)
                ->delete();

            foreach ($transactions as $k => $v) {
                $row = array();
                $row['createtime'] = $v['created_at'];
                $row['kind'] = $v['kind'];
                $row['update_time'] = $v['processed_at'];
                $row['status'] = $v['status'];
                $row['order_id'] = $v['order_id'];
                $row['gateway'] = $v['gateway'];
                $row['message'] = $v['message'];
                $row['created_at'] = $v['created_at'];
                $row['authorization'] = $v['authorization'];
                $row['amount'] = $v['amount'];
                $row['currency'] = $v['currency'];
                if (isset($v['payment_id'])) {
                    $row['payment_id'] = $v['payment_id'];
                }
                $row['transactions_id'] = $v['id'];
                Db::connect('DULIZHAN')
                    ->name('order_transactions')->insert($row);
            }
        }
    }

}
